package plugins.septwolves;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;

import com.meiya.common.string.StringUtil;
import com.zhangwoo.spider.client.process.AnalyserTemplate;
import com.zhangwoo.spider.po.Conversation;
import com.zhangwoo.spider.po.UrlRequest;

/**
 * 采集评论
 * 
 */
public class SeptwolvesTmallRate implements AnalyserTemplate {
	Logger logger = Logger.getLogger(this.getClass().getName());

	public boolean isMatchTemplate(UrlRequest urlReq, String html) {
		if (urlReq.getUrl().indexOf("http://rate.tmall.com") != -1)
			return true;
		return false;
	}

	public List<Conversation> findConversations(UrlRequest urlReq, String html,
			Document docHtml) {
		List<Conversation> convsResults = new ArrayList<Conversation>();
		String expRate = "\\{\"aliMallSeller\".*?\"userVipPic\":\"\"\\}";
		List<String[]> r = StringUtil.matchAll(html, expRate);
		for (String[] o : r) {
			Conversation result = new Conversation();
			result.setTitle(urlReq.getTitle());
			result.setContent(StringUtil.match(o[0],
					"\"rateContent\":\"(.*?)\",\"rateDate\"")[1]+ " "
					+ StringUtil.match(o[0],
									"\"serviceRateContent\":\"(.*?)\",\"tamllSweetLevel\"")[1]);
			result.setPublishTime(StringUtil.match(o[0],
					"\"rateDate\":\"(.*?)\"")[1]);
			result.setAuthor(StringUtil.match(o[0],
					"\"displayUserNick\":\"(.*?)\"")[1]);
			result.setSelfLink(urlReq.getUrl() + "##"
					+ StringUtil.match(o[0], "\"id\":(\\d+),")[1]);
			result.setComment(StringUtil.match(o[0], "\"userInfo\":\"(.*?)\",")[1]
					+ " "
					+ StringUtil.match(o[0], "\"auctionSku\":\"(.*?)\",")[1]);
			convsResults.add(result);
		}
		return convsResults;
	}

	public List<UrlRequest> findLinks(UrlRequest urlReq, String html,
			Document docHtml) {
		List<UrlRequest> links = new ArrayList<UrlRequest>();
		String[] pages=StringUtil.match(html, "\"lastPage\":(\\d+),\"page\":(\\d+)");
		int lastPage = Integer.valueOf(pages[1]);
		int page = Integer.valueOf(pages[2])+1;
		int currPage=page-1;
		try {
			for(;page<=lastPage;page++){
				UrlRequest u = (UrlRequest) urlReq.clone();
				u.setUrl(urlReq.getUrl().replace("currentPage="+currPage, "currentPage="+page));
				u.setTitle(urlReq.getTitle());
				if(!links.contains(u))	links.add(u);
			}
		} catch (Exception e) {
			logger.error("SeptwolvesTmallRate error",e);
		}
		return links;
	}
}
